/**
 * Created by judasnow on 20/06/2017.
 */

import {
    LOGIN_SUCCESS,
    LOGOUT_SUCCESS,
    GET_CURRENT_USER_OK
} from '../mutations'
import {saveCookie, getCookie} from '../../util/auth.js'
import { AUTH_COOKIE_NAME } from '../../config'

class CurrentUser {
    constructor(id, name) {
        this.id = id;
        this.name = name;
    }
}

const state = {
    token: getCookie(AUTH_COOKIE_NAME),
    // 已经登录的情况在哪里触发当前登录用户的加载
    crtUser: undefined
};

const actions = {};

const mutations = {
    [LOGIN_SUCCESS] (state, data) {
        // TODO data 类型如何验证 ???
        state.token = data.session.token;
        state.crtUser = data.current_user;
        saveCookie(AUTH_COOKIE_NAME, state.token, {maxAge: data.session.expires_in});
    },
    [LOGOUT_SUCCESS] (state, data) {
        state.token = '';
        state.crtUser = undefined;
    },
    [GET_CURRENT_USER_OK] (state, data) {
        state.crtUser = data
    }
};

export default {
    state,
    actions,
    mutations,
}